<?php

// tail-technology

/**
 * API测试
 */
define("TOKEN", "tail2m");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"]; // 随机字符串

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

	// 检查签名
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"]; // 时间戳
        $timestamp = $_GET["timestamp"]; // 时间戳
        $nonce = $_GET["nonce"];		 // 随机数

		/** 校验规则
		 * 1）将token、timestamp、nonce三个参数进行字典序排序
		 * 2）将三个参数字符串拼接成一个字符串进行sha1加密
		 * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		 */
		$token  = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}
		return false;
	}
}